/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.carbondata.processing.newflow.dictionary;

import java.util.Map;

import org.apache.carbondata.core.devapi.DictionaryGenerationException;
import org.apache.carbondata.core.devapi.DictionaryGenerator;
import org.apache.carbondata.core.devapi.GeneratingBiDictionary;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class InMemBiDictionary<K, V> extends GeneratingBiDictionary<K, V> {

  private BiMap<K, V> biMap;

  /**
   * Constructor to create a new dictionary, dictionary key will be generated by specified generator
   * @param generator
   */
  public InMemBiDictionary(DictionaryGenerator generator) {
    super(generator);
    biMap = HashBiMap.create();
  }

  /**
   * Constructor to create a pre-created dictionary
   * @param preCreatedDictionary
   */
  public InMemBiDictionary(Map<K, V> preCreatedDictionary) {
    super(new DictionaryGenerator<K, V>() {
      @Override
      public K generateKey(V value) throws DictionaryGenerationException {
        // Since dictionary is provided by preCreated, normally it should not come here
        throw new DictionaryGenerationException(
            "encounter new dictionary value in pre-created dictionary:" + value);
      }
    });
    biMap = HashBiMap.create(preCreatedDictionary);
  }

  @Override
  public K getKey(V value) {
    return biMap.inverse().get(value);
  }

  @Override
  public V getValue(K key) {
    return biMap.get(key);
  }

  @Override
  protected void put(K key, V value) {
    // dictionary is immutable, it is append only
    assert (!biMap.containsKey(key));
    assert (!biMap.containsValue(value));
    biMap.put(key, value);
  }

  @Override
  public int size() {
    return biMap.size();
  }
}
